package com.fresh.api;

import java.io.PrintWriter;
import java.sql.Timestamp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fresh.common.annotation.IgnoreAuth;
import com.fresh.dao.VerifyDao;
import com.fresh.entity.AntifraudUser;
import com.fresh.entity.ChsiCaptchaEntity;
import com.fresh.entity.ChsiLoginEntity;
import com.fresh.entity.ChsiQueryEntity;
import com.fresh.entity.ChsiResultEntity;
import com.fresh.entity.ZxExternalData;
import com.fresh.entity.ZxExternalSource;
import com.fresh.service.VerifyService;
import com.fresh.utils.Base64Utils;
import com.fresh.utils.HttpUtils;
import com.fresh.utils.PropertiesUtils;
import com.fresh.utils.Sequence;
import com.google.gson.Gson;

/**
 * 学信网接口调用
 * 
 * @author 学信网接口调用
 * @version 1.0
 * @date 2017年10月26日下午5:40:14 福乐康 Copyright© All Reserved 官方网站：www.flksh.com
 *       未经授权不得进行修改、复制、出售及商业使用
 */
@RequestMapping({ "/ch" })
@Controller
public class ChsiController {
	private static final Logger log = LoggerFactory
			.getLogger(ChsiController.class);
	
	@Autowired
	private VerifyService verifyService;
	
	
	@Autowired
	private VerifyDao verifyDao;

	@IgnoreAuth
	@RequestMapping({ "setChsi" })
	public String toChsi(HttpServletRequest request, AntifraudUser user)
			throws Exception {
		request.setAttribute("id", user.getId());
		log.info("#toChsi() 进入学信网查询页！");
		return "/buyer/chsi";
	}
	
	
	@ResponseBody
	@IgnoreAuth
	@RequestMapping({ "getCode" })
	public String getCode(HttpServletRequest request)
			throws Exception {
		log.info("#getCode() 开始获取验证码：{}");
		
		Gson gson=new Gson();
		
		try {
		//学信网接口url
		String chsi_url = PropertiesUtils.getProperty("ssmh_url");
		String partner_code = PropertiesUtils.getProperty("partner_code");
		String partner_key = PropertiesUtils.getProperty("partner_key");
		
		//获取task_id接口;
		String chsi_query_url=chsi_url+"login.fields.query/v1?partner_code="+partner_code+"&partner_key="+partner_key+"&channel_type=CHSI&channel_code=000000";
		String resqueryJson = HttpUtils.doPostx(chsi_query_url, null, null, 3, 10, "utf-8");
		ChsiQueryEntity chsiquery=gson.fromJson(resqueryJson, ChsiQueryEntity.class);
		log.info("#getCode() taskid：{}"+chsiquery.getTask_id());
		
		//获取验证码接口;
		if (!chsiquery.getCode().equals("2005")) {
			return "验证码获取失败！";
		}
		String chsi_captcha_url=chsi_url+"chsi.captcha/v1?partner_code="+partner_code+"&partner_key="+partner_key+"&task_id="+chsiquery.getTask_id();
		String rescaptchaJson = HttpUtils.doPostx(chsi_captcha_url, null, null, 3, 10, "utf-8");
		ChsiCaptchaEntity chsicaptcha=gson.fromJson(rescaptchaJson, ChsiCaptchaEntity.class);
		
		String imgName=Base64Utils.GenerateImage(chsicaptcha.getData());
		String getImg_url = PropertiesUtils.getProperty("getImg_url");
		String result=imgName+".jpg"+"="+chsicaptcha.getTask_id()+"="+getImg_url;
		return result;
		} catch (Exception e) {
		}
		return null;
		
	}
	
	@IgnoreAuth
	@RequestMapping(value = "loginChsi", produces = "application/json;charset=utf-8")
	public String loginChsi(HttpServletRequest request,ChsiLoginEntity chsiLoginEntity,HttpServletResponse response)
			throws Exception {
		
		
		try {
			request.setAttribute("id", chsiLoginEntity.getId());
			Gson gson=new Gson();
			log.info("#loginChsi() 开始登录学信网查询信息！查询用户：{}" + gson.toJson(chsiLoginEntity));
			ZxExternalData zxExternalData=null;
			if (request.getSession().getAttribute("USER_SCORE")!=null) {
				 zxExternalData=(ZxExternalData) request.getSession().getAttribute("USER_SCORE");
			
				log.info("#getGs() 当前用户:" + gson.toJson(zxExternalData));
			
			}else{
				 PrintWriter out = response.getWriter();  
			        out.println("<html>");      
			        out.println("<script>");      
			        out.println("window.open ('"+request.getContextPath()+"/index','_top')");      
			        out.println("</script>");      
			        out.println("</html>");    
				return null;
			}

			//学信网接口url
			String chsi_url = PropertiesUtils.getProperty("ssmh_url");
			String partner_code = PropertiesUtils.getProperty("partner_code");
			String partner_key = PropertiesUtils.getProperty("partner_key");
			
			//登录学信网查询信息接口
			String chsi_login_url=chsi_url+"chsi.acquire/v1?partner_code="+partner_code+"&partner_key="+partner_key+"&user_name="+chsiLoginEntity.getUser_name()+"&user_pass="+chsiLoginEntity.getUser_pass()+"&task_id="+chsiLoginEntity.getTask_id()+"&auth_code="+chsiLoginEntity.getAuth_code()+"";
			String resloginJson = HttpUtils.doPostx(chsi_login_url, null, null, 3, 10, "utf-8");
			ChsiResultEntity chsiResultEntity=gson.fromJson(resloginJson, ChsiResultEntity.class);
			
			if (chsiResultEntity.getCode().equals("102") ||chsiResultEntity.getCode().equals("112") || chsiResultEntity.getCode().equals("113") || chsiResultEntity.getCode().equals("200") || chsiResultEntity.getCode().equals("1") ||chsiResultEntity.getCode().equals("1070") || chsiResultEntity.getCode().equals("2001") || chsiResultEntity.getCode().equals("2901") ||chsiResultEntity.getCode().equals("2902") || chsiResultEntity.getCode().equals("2006")) {
				request.setAttribute("error", chsiResultEntity.getMessage());
				return "/buyer/chsiResult";
			}
			
			if (!resloginJson.contains("data") || chsiResultEntity.getCode().equals("100")) {
				boolean flag=true;
				
				while (flag) {
					//调查询结果接口
					String chsi_task_url=chsi_url+"task.query/v1?partner_code="+partner_code+"&partner_key="+partner_key+"&task_id="+chsiResultEntity.getTask_id();
					String restaskJson = HttpUtils.doPostx(chsi_task_url, null, null, 3, 10, "utf-8");
					log.info("#loginChsi() 学信网查询结果接口:" + restaskJson);
					ChsiResultEntity chsiResultEntity2=gson.fromJson(restaskJson, ChsiResultEntity.class);
					request.setAttribute("chsiList", chsiResultEntity2.getData().getEducation_info());
					
					if (chsiResultEntity2.getCode().equals("102") ||chsiResultEntity2.getCode().equals("112") || chsiResultEntity2.getCode().equals("113") || chsiResultEntity2.getCode().equals("200") || chsiResultEntity2.getCode().equals("1") ||chsiResultEntity2.getCode().equals("1070") || chsiResultEntity2.getCode().equals("2001") || chsiResultEntity2.getCode().equals("2901") ||chsiResultEntity2.getCode().equals("2902")) {
						request.setAttribute("error", chsiResultEntity.getMessage());
						return "/buyer/chsiResult";
					}
					
					//学信网信息入库
					setSource(zxExternalData.getId(), restaskJson);
					
					//扣款
					verifyService.debit(request, "2");
					return "/buyer/chsiResult";
				}
				
			}
			
			log.info("#loginChsi() 登录学信网查询信息接口:" + gson.toJson(chsiResultEntity));
			if (!chsiResultEntity.getCode().equals("0")) {
				request.setAttribute("error", chsiResultEntity.getMessage());
				return "/buyer/chsiResult";
			}
			
			//学信网信息入库
			setSource(zxExternalData.getId(), resloginJson);
			
			//扣款
			verifyService.debit(request, "2");
			request.setAttribute("chsiList", chsiResultEntity.getData().getEducation_info());
			return "/buyer/chsiResult";
		} catch (Exception e) {
			request.setAttribute("error", "服务器忙请稍后重试！");
			return "/buyer/chsiResult";
		}
		
		
	}


	
	public void setSource(String externalId,String json){
		Timestamp now = new Timestamp(System.currentTimeMillis());
		
		ZxExternalSource zxExternalSource = new ZxExternalSource();
		zxExternalSource.setId(Sequence.nextId());
		zxExternalSource.setType(PropertiesUtils.getProperty("chsi_type")); //2：学信网
		zxExternalSource.setVersion("v1");
		zxExternalSource.setExternalId(externalId);
		zxExternalSource.setDataSource(json);
		zxExternalSource.setIntertype(Integer.valueOf(3));
		zxExternalSource.setCreateTime(now);
		verifyService.saveSource(zxExternalSource);
	}
	

}
